<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="批号" prop="batchNo">
            <el-tooltip
              class="item"
              effect="dark"
              content="支持多个批号的输入,输入数字,图表中间提供多个选择框,仅支持选择一个去显示图表"
              placement="bottom"
            >
              <el-input
                type="textarea"
                v-model="queryParams.batchNo"
                placeholder="请输入多个批号"
                clearable
              />
            </el-tooltip>
          </el-form-item>
          <el-form-item label="起始时间" prop="startTime">
            <el-date-picker
              v-model="queryParams.startTime"
              type="datetime"
              format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="截止时间" prop="endTime">
            <el-date-picker
              v-model="queryParams.endTime"
              type="datetime"
              format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >查询</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row :gutter="8">
      <el-col :span="14">
        <div style="height: 420px" ref="lineMap" id="lineMap"></div>
      </el-col>
      <el-col :span="10">
        <div style="height: 420px" ref="raderMap" id="raderMap"></div>
      </el-col>
    </el-row>
    <el-row style="margin-top: 20px">
      <el-col :span="24">
        <el-table v-loading="loading" :data="listDatas">
          <el-table-column
            prop="areaId"
            label="类型"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="radarArea"
            label="相似度"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="correctRate"
            label="机场"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="locationDeviation"
            label="活动范围"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="distanceDeviation"
            label="活动时间"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="distanceDeviationUnAbs"
            label="速度"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="directionDeviation"
            label="航线"
            align="center"
          ></el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="recordDataEdit(scope.row)"
                >编辑</el-button
              >
              <el-button
                v-if="scope.row.parentId != 0"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="recordDataDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import * as echarts from "echarts";
import "@/assets/styles/dataoverview.scss";
import moment from "moment";
import { worldMap } from "@/assets/mapJson/worldMap";
import { nameMapData } from "@/assets/mapJs/common";
import ShowModal from "./compoments/showModal";
//注册中国地图
echarts.registerMap("worldMap", worldMap, {});
import {
  getDataoverViewList,
  getListPathByFlightType,
  getDict,
  getFlightFrequencyList,
  getListByUniqueBatchNoList,
  getListAreaStat,
  exportAreaStat,
  getStatAreaHourDeviation,
  getHistoryPlaneAuxilList,
  getHistoryAuxilList,
  getBatchModDeviationStatDelModal,
  getBatchModDeviationStatListModal2,
} from "@/api/service";
export default {
  name: "",
  components: {},
  data() {
    return {
      loading: false,
      // 显示搜索条件
      showSearch: true,
      tabsValue: "",
      messageRelate: null, //关联值
      tabPosition: "hot",
      channels: [],
      dataVolumes: [],
      hotDoatData: [], //热力图数据
      listDatas: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        startTime: moment().subtract(1, "days").format("YYYY-MM-DD HH:mm"),
        endTime: moment(new Date()).format("YYYY-MM-DD HH:mm"),
        sourceId: "8203",
      },
      sjzl: 0,
      mapGeoData: null,
      forChartsMapData: [],
      echartsData: [],
      selectStartMonth: moment().startOf("month").format("YYYY-MM-DD"),
      selectEndMonth: moment().endOf("month").format("YYYY-MM-DD"),
      graph: null,
      data: [],
      newDataPlane: [],
      flightDotData: [],
      historyArea: [],
      leftEchartsData: [],
      leftTableList: [],
      showHistoryList: [],
      showHistoryList1: [],
      showHistoryList2: [],
      dataList: [],
      sourceId: "8203",
      newTableData: [], //实时右边表格
      //展示弹窗
      modalListFromArea: [],
      modelOpen: false,
      radarData: [],
      btnVisible: false, //展示的切换
      hisSimilarsFilghtAll: [],
      dataSouceJudge: [],
      initRadarData: [],
      hisFilghtAllData: [],
    };
  },
  mounted() {
    getDict("channel_type").then((res) => {
      console.log("channel_type", res.data);
      if (res.code === 200) {
        const data = res.data.map((item) => {
          return {
            value: item.dictValue,
            label: item.dictLabel,
          };
        });
        this.channels = data;
      }
    });

    this.getItineraryData();
    this.initEcharts();
  },
  methods: {
    initEcharts() {
      //航迹图
      const lineMap = echarts.init(this.$refs.lineMap);
      let lineMapOption = {
        backgroundColor: "#1a203a",
        title: {
          // text: '航迹叠加图',
          subtext: "",
          left: "center",
          textStyle: {
            color: "#fff",
          },
        },
        tooltip: {
          trigger: "item",
          formatter: function (params, ticket, callback) {
            // if (params.seriesType == 'effectScatter') {
            //   return '线路：' + params.data.name + ''; // + params.data.value[2]
            // } else if (params.seriesType == 'lines') {
            //   return params.data.fromName + '>' + params.data.toName + '<br />'; //params.data.value
            // } else {
            //   return params.name;
            // }
          },
        },
        legend: {
          orient: "vertical",
          top: "bottom",
          left: "right",
          textStyle: {
            color: "#fff",
          },
          selectedMode: "multiple",
        },
        nameMap: nameMapData,
        geo: {
          map: "worldMap",
          label: {
            emphasis: {
              show: true,
              color: "#fff",
            },
          },
          regions: [
            {
              name: "南海诸岛",
              itemStyle: {
                // 隐藏地图
                normal: {
                  opacity: 0, // 为 0 时不绘制该图形
                },
              },
              label: {
                show: false, // 隐藏文字
                fontSize: 0,
              },
            },
          ],
          // 把中国地图放大了1.2倍
          zoom: 6,
          roam: true,
          center: [124.775265, 28.849163],
          itemStyle: {
            normal: {
              // 地图省份的背景颜色
              areaColor: "rgba(20, 21, 87,0.6)",
              borderColor: "#195BB9",
              borderWidth: 1,
            },
            emphasis: {
              areaColor: "#2B91B7",
            },
          },
        },
        series: this.seriesFormatShow(),
      };
      document.getElementById("lineMap").removeAttribute("_echarts_instance_");
      lineMap.setOption(lineMapOption);

      //雷达图  raderMap
      const raderMap = echarts.init(this.$refs.raderMap);
      let raderMapOption = {
        tooltip: {
          trigger: "axis",
        },
        title: {
          text: "目标类型统计",
          textStyle: {
            color: "#ccc",
          },
        },
        radar: {
          indicator: [
            { name: "机场", max: 1 },
            { name: "活动范围", max: 1 },
            { name: "活动时间", max: 1 },
            { name: "速度", max: 1 },
            { name: "航线", max: 1 },
          ],
        },
        series: [
          {
            type: "radar",
            label: {
              show: true,
            },
            areaStyle: {},
            data: [
              {
                value:
                  this.radarData?.length > 0
                    ? this.radarData
                    : this.initRadarData,
              },
            ],
          },
        ],
      };
      document.getElementById("raderMap").removeAttribute("_echarts_instance_");
      raderMap.setOption(raderMapOption);
    },

    //雷达图数据
    handleDisplayMap(record) {
      // setRecordData(record?.targetCode);
      this.radarData([
        record?.airPortScore?.toFixed(2),
        record?.activeAreaScore?.toFixed(2),
        record?.activeTimeScore?.toFixed(2),
        record?.speedScore?.toFixed(2),
        record?.pathScore?.toFixed(2),
      ]);
      if (!btnVisible) {
        getHistoryPlaneAuxilListHandle(record?.targetCode);
      } else {
        this.btnVisible = false;
      }
    },

    // 航迹图series
    seriesFormatShow() {
      let series = [];
      this.flightDotData &&
        this.flightDotData
          .filter((item) => {
            return item?.length > 0;
          })
          //过滤数据空的航迹点
          .map((iten) => {
            if (iten.length > 1) {
              series.push(
                {
                  type: "lines", //第一条实线
                  coordinateSystem: "geo", // 这句的意思是连线是基于地理坐标的,geo组件将在下面给出
                  polyline: true, // 这表示连线是否为多端点的连线
                  data: [
                    {
                      coords: iten,
                    },
                  ],
                  lineStyle: {
                    color: "block",
                    width: 2,
                  },
                  effect: {
                    //线特效，小飞机
                    constantSpeed: 10,
                    show: true,
                    color: "yellow", //#00EAFF
                    symbolSize: 15,
                    symbol: planePath,
                  },
                  progressiveThreshold: 500,
                  progressive: 200,
                },
                {
                  type: "lines", //第二条虚线
                  coordinateSystem: "geo", // 这句的意思是连线是基于地理坐标的,geo组件将在下面给出
                  polyline: true, // 这表示连线是否为多端点的连线
                  data: [
                    {
                      coords: iten,
                    },
                  ],
                  lineStyle: {
                    color: "#fff",
                    width: 2,
                    type: "dashed",
                  },
                  progressiveThreshold: 500,
                  progressive: 200,
                }
              );
            }
          });

      this.flightDotData1 &&
        this.flightDotData1
          .filter((item) => {
            return item?.length > 0;
          })
          .map((iten) => {
            if (iten.length > 1) {
              series.push(
                {
                  type: "lines", //第一条实线
                  coordinateSystem: "geo", // 这句的意思是连线是基于地理坐标的,geo组件将在下面给出
                  polyline: true, // 这表示连线是否为多端点的连线
                  data: [
                    {
                      coords: iten,
                    },
                  ],
                  lineStyle: {
                    color: "block",
                    width: 2,
                  },
                  effect: {
                    //线特效，小飞机
                    constantSpeed: 10,
                    show: true,
                    color: "red", //#00EAFF
                    symbolSize: 15,
                    symbol: planePath,
                  },
                  progressiveThreshold: 500,
                  progressive: 200,
                },
                {
                  type: "lines", //第二条虚线
                  coordinateSystem: "geo", // 这句的意思是连线是基于地理坐标的,geo组件将在下面给出
                  polyline: true, // 这表示连线是否为多端点的连线
                  data: [
                    {
                      coords: iten,
                    },
                  ],
                  lineStyle: {
                    color: "#fff",
                    width: 2,
                    type: "dashed",
                  },
                  progressiveThreshold: 500,
                  progressive: 200,
                },
                {
                  // name: '基地',
                  type: "effectScatter",
                  coordinateSystem: "geo",
                  data: convertData(forChartsMapData),
                  colorBy: "data",
                  zlevel: 2,
                  rippleEffect: {
                    period: 4,
                    scale: 4,
                    brushType: "stroke",
                  },
                  symbolSize: 6,
                  symbol: "circle",
                  label: {
                    normal: {
                      show: true, //显示市区标签
                      textStyle: { color: "#ccc", fontSize: "16px" }, //省份标签字体颜色
                      formatter: (params) => {
                        return params?.data?.[3];
                      },
                      position: ["-130%", "150%"],
                    },
                    emphasis: {
                      //对应的鼠标悬浮效果
                      show: false, //关闭文字 （这东西有问题得关）
                      textStyle: { color: "transparent" },
                    },
                  },
                  // itemStyle: {
                  //   normal: {
                  //     borderWidth: 7, //区域边框宽度
                  //     borderColor: '#fc8452', //区域边框颜色
                  //     areaColor: '#fc8452', //区域颜色
                  //   },
                  // },
                }
              );
            }
          });

      series.push({
        type: "lines",
        polyline: true,
        coordinateSystem: "geo",
        lineStyle: {
          type: "dashed",
          color: "yellowGreen",
          width: 2,
          opacity: "0.5",
        },
        effect: {
          show: true,
          trailLength: 0.1,
          symbol: "none",
          symbolSize: 8,
        },
        data: this.historyArea,
      });
      return series;
    },

    //获取历史的数据
    getHistoryData(val) {
      let data = {
        batchNo: val,
        endTime: getEndTime,
        startTime: getStartTime,
      };
      getHistoryAuxilList(data).then((res) => {
        if (res.code == 200) {
          this.dataSouceJudge = res.data;
          let dataActualData = res.data?.self?.locationRadar.map((item) => {
            return [item?.longitude, item?.latitude];
          });

          let dataSimilarsData = res.data?.similars?.map((item) => {
            return item.similarBatch?.locationRadar.map((iten) => {
              return [iten?.longitude, iten?.latitude];
            });
          });
          let data = [
            res.data?.similars[0]?.airPortScore?.toFixed(2),
            res.data?.similars[0]?.activeAreaScore?.toFixed(2),
            res.data?.similars[0]?.activeTimeScore?.toFixed(2),
            res.data?.similars[0]?.speedScore?.toFixed(2),
            res.data?.similars[0]?.pathScore?.toFixed(2),
          ];
          this.initRadarData = data;

          this.hisSimilarsFilght = dataSimilarsData;
          this.hisFilghtAllData.push(dataActualData);
        } else {
          message.warning(res?.msg);
        }
      });
    },

    //根据类型获取所有的历史航迹
    getHistoryPlaneAuxilListHandle(type) {
      getHistoryPlaneAuxilList(type).then((res) => {
        if (res.code === 200) {
          let dataSimilarsData = res.data?.map((item) => {
            return item?.locationRadar?.map((iten) => {
              return [iten?.longitude, iten?.latitude, iten?.batchNo];
            });
          });
          this.hisSimilarsFilghtAll = dataSimilarsData;
          this.btnVisible = true;
        } else {
          this.btnVisible = false;
        }
      });
    },

    //历史关联数据
    handleDisplayMap(record) {
      let data = {
        uniqueBatchNo: record?.uniqueBatchNo,
      };
      getListByUniqueBatchNoList(data).then((res) => {
        console.log(502, res);
        if (res.code == 200) {
          this.leftEchartsData = res.data?.locationRadarDeviations || [];
          let showItnerList = res.data?.locationRadar?.map((item) => {
            return [item?.longitude, item?.latitude, item?.locationDeviation];
          });
          let showItnerList1 = res.data?.locationRadar?.map((item) => {
            return [item?.longitude, item?.latitude];
          });
          //添加辅助飞行线
          let showItnerList2 = res.data?.locationReals?.map((item) => {
            return [item?.longitude, item?.latitude];
          });
          this.leftTableList = res.data?.locationRadarDeviations || [];
          this.newDataPlane = res.data?.locationRadarDeviations
            ? res.data?.locationRadarDeviations.reverse()
            : [];
          if (historyList.length > 0) {
            this.showHistoryList = showItnerList;
            this.showHistoryList1 = [showItnerList1];
            this.showHistoryList2 = [showItnerList2];
          } else {
            this.showHistoryList = [];
            this.showHistoryList1 = [];
            this.showHistoryList2 = [];
          }
        }
      });
    },

    //将数据处理给到航迹
    getItineraryData() {
      console.log(570);
      let data = this.newDataPlane.map((item) => {
        if (item?.longitude && item?.latitude) {
          return [item?.longitude, item?.latitude];
        }
      });
      console.log(620, data);
      this.flightDotData.push(data);
      console.log(621, this.flightDotData);
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    filterData(value) {
      let data =
        this.frequencyData &&
        this.frequencyData.filter((item) => {
          return item?.dictValue == value;
        });
      console.log("filterData", data[0]?.dictLabel, frequencyData);
      return data[0]?.dictLabel;
    },
    convertData(data) {
      var res = [];
      for (var i = 0; i < data.length; i++) {
        var geoCoord = this.mapGeoData[data[i].name];
        if (geoCoord) {
          res.push(geoCoord.concat(data[i].value).concat(data[i].name));
        }
      }
      return res;
    },
    //表格数据
    getList() {
      getBatchModDeviationStatListModal2(7).then((res) => {
        if (res.code === 200) {
          res.data.forEach((iten, index) => {
            return (iten["idKey"] = index + 1);
          });
          this.listDatas = res.data;
        }
      });
    },
    //删除
    recordDataDelete(row) {
      const { id } = row;
      getBatchModDeviationStatDelModal(id).then((res) => {
        if (res.code == 200) {
          getList();
        }
      });
    },
  },
};
</script>
<style scoped>
::v-deep .el-statistic .con .number {
  color: #c4ebff;
}
::v-deep .topH2Style .con .number {
  font-size: 32px;
}
::v-deep .el-radio-group {
  width: 100%;
}
::v-deep .el-radio-group .el-radio-button {
  width: 50%;
}
::v-deep .el-radio-group .el-radio-button .el-radio-button__inner {
  width: 100%;
}
</style>
